package pub.cleangao.codegen.enquiry;

import pub.cleangao.codegen.GenConfigHolder;
import pub.cleangao.codegen.sqlexe.SqlHelper;
import pub.cleangao.common.util.BeanUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import java.util.stream.Collectors;


public abstract class TableEnquiry implements Enquiry {


    protected final GenConfigHolder config;
    protected final ColumnEnquiry columnEnquiry;
    protected List<String> schemaTables;

    public TableEnquiry(GenConfigHolder config, ColumnEnquiry columnEnquiry) {
        this.config = config;
        this.columnEnquiry = columnEnquiry;
    }


    /**
     * ShowTablesSql
     */
    public abstract String getShowTablesSql();

    /**
     * 当前表信息
     */
    public abstract TableInfo buildTableInfo(Map<String, Object> tableMap);


    /**
     * 表的全部信息
     */
    public List<TableInfo> getTableInfos() {
        List<Map<String, Object>> resultList = SqlHelper.runSql(config, getShowTablesSql());
        List<TableInfo> tablesList = new ArrayList<TableInfo>(resultList.size());
        for (Map<String, Object> rowMap : resultList) {
            TableInfo tableInfo = this.buildTableInfo(rowMap);
            String tableName = tableInfo.getTableName();
            List<ColumnInfo> columnInfos = columnEnquiry.getColumnInfos(tableName);
            tableInfo.setColumnInfos(buildJavaColumnInfos(columnInfos, JavaColumnInfo::new));
            tablesList.add(tableInfo);
        }
        return tablesList;
    }


    private <T> List<T> buildJavaColumnInfos(List<ColumnInfo> columnInfos, Supplier<T> supplier) {
        return columnInfos.stream()
                .map(columnDefinition -> {
                    T t = supplier.get();
                    BeanUtil.copyPropertiesIgnoreNull(columnDefinition, t);
                    return t;
                }).collect(Collectors.toList());
    }


    public void setSchemaTables(String tablesStr) {
        if (schemaTables == null) {
            schemaTables = new ArrayList<>();
        }
        if (tablesStr == null || tablesStr.isEmpty()) {
            return;
        }
        if (tablesStr.contains(",")) {
            String[] tableArr = tablesStr.split(",");
            for (String table : tableArr) {
                schemaTables.add(table.trim());
            }
        } else {
            schemaTables.add(tablesStr.trim());
        }
    }


}
